package org.lc.gateway.filter;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

import cn.hutool.json.JSONUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.lc.gateway.util.JwtTokenUtil;
import org.lc.platform.base.constant.AuthConstant;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.oauth2.jwt.ReactiveJwtDecoder;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import com.nimbusds.jose.JWSObject;

import cn.hutool.core.util.StrUtil;
import reactor.core.publisher.Mono;

/**
 * 将登录用户的JWT转化成用户信息的全局过滤器
 * //
 */
@Slf4j
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Resource
    private ReactiveJwtDecoder jwtDecoder;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = JwtTokenUtil.getJwtFromRequest(exchange.getRequest());
        Map<String, String> addHeaders = new HashMap<>();
        if (!StrUtil.isEmpty(token)) {
            /* 解析token获取相关值 */
            var user = JwtTokenUtil.getJwtMapUser(jwtDecoder, token);
            addHeaders.put(AuthConstant.HEADER_USER, URLEncoder.encode(JSONUtil.toJsonStr(user), StandardCharsets.UTF_8));
        }
        Consumer<HttpHeaders> httpHeaders = httpHeader -> {
            addHeaders.forEach(httpHeader::set);
        };
        ServerHttpRequest request = exchange.getRequest().mutate().headers(httpHeaders).build();
        exchange = exchange.mutate().request(request).build();
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}